package com.education;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.svg.opengl.texture.atlas.bitmap.SVGBitmapTextureAtlasTextureRegionFactory;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.education.*;

import android.content.Context;

public class WordsDictionary {
	
	private JSONArray dict;
	private Queue<int[]> wordsQueue;
	public class Word {
		public int[] letters;
		public Sound sound;
		public Sprite image;
		public Word(int[] pLetters, Sound pSound, Sprite pImage)
		{
			letters = pLetters;
			sound = pSound;
			image = pImage;
		}		
	}
	
	private BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas;
	private MainActivity mActivity;
	public WordsDictionary(MainActivity activity, String dictFile) throws JSONException
	{
		this.mActivity = activity;
		this.wordsQueue = new LinkedList<int[]>();
		dict = new JSONObject(Utilities.loadJSONFromAsset(this.mActivity, dictFile)).getJSONArray("dictionary");
	}
	
	public Word getWord()
	{
		Integer randomIndex = 0;
	    JSONObject wordJSON = null;
	    Boolean wordInQueue = true;
	    int[] letters = new int[1];
		try {
			while(wordInQueue)
			{
				randomIndex = new Random().nextInt(dict.length()-1);
				wordJSON = dict.getJSONObject(randomIndex);
				letters = new int[wordJSON.getJSONArray("word").length()];
				for (int i = 0; i<wordJSON.getJSONArray("word").length(); i++)
				{
					letters[i] = wordJSON.getJSONArray("word").optInt(i, -1);
				}
				if (wordsQueue!=null)
				{
					wordInQueue = wordsQueue.contains(letters);
				} else
				{
					wordInQueue=false;
				}
			}
			Word word = JSONToWord(wordJSON);
			wordsQueue.offer(letters);
			return word;
		} catch (JSONException e) {
			// TODO Обработка ошибки чтения JSON из словаря
			e.printStackTrace();		
		} catch (IOException e) {
			// TODO Обработка ошибки чтения JSON файла словаря
			e.printStackTrace();
		}
	    return null;
	}
	
	private Word JSONToWord(JSONObject json) throws JSONException, IOException
	{
		SVGBitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(mActivity.getTextureManager(), 2048, 1024, TextureOptions.NEAREST);
		ITextureRegion wordPicAtlas = SVGBitmapTextureAtlasTextureRegionFactory.createFromAsset(mBuildableBitmapTextureAtlas, mActivity, json.get("image").toString(), (int)(800*mActivity.scaleRatio), (int)(800*mActivity.scaleRatio));
		try {
			this.mBuildableBitmapTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(1, 1, 1));
		} catch (TextureAtlasBuilderException e) {
			// TODO TextureAtlasBuilderException Auto-generated catch block
			e.printStackTrace();
		}
		
		this.mBuildableBitmapTextureAtlas.load();
		
		Sprite wordpic  = new Sprite(0, -800*mActivity.scaleRatio, wordPicAtlas, mActivity.getVertexBufferObjectManager())
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				return false;
			}
		};
		
		int letters[] = new int[json.getJSONArray("word").length()];
		for (int i =0; i<json.getJSONArray("word").length(); i++)
		{
			letters[i] = json.getJSONArray("word").optInt(i, -1);
		}
		
		Word word = new Word(
				letters,
				SoundFactory.createSoundFromAsset(mActivity.getSoundManager(), mActivity.getApplicationContext(),Alphabet.badSound),
				wordpic
				);
		return word;
	}
}
